#coding=utf-8 
import json
import status
import reg_user
import login

# 新的客户端连接
def connect(client,ip_str):
    print "connect fd:{} ip:{}".format(client,ip_str)


# 客户端断开连接
def disconnect(client,ip_str):
    print "disconnect fd:{} ip:{}".format(client,ip_str)


# 用于校验请求对应的参数字段
req_params = {"reg_user":["name","passwd"],
                "login":["name","passwd"]}
 
# 接收客户端数据
def receive(client,ip_str,data):
#    print "receive fd:{} ip:{} data:{}".format(client,ip_str,data)
    # 返回给调用者【默认失败关闭连接】
    ret_data = [{},[],{},True]
    try:
        # 解析json字符串
        data = json.loads(data)
        if not data.has_key("req"):
            print "has not key <req>"
            ret_data[0]["status"] = status.REQ_ERR
        elif data["req"] not in req_params.keys():
            print "req handler not exist"
            ret_data[0]["status"] = status.REQ_ERR
        elif set(req_params[data["req"]]).difference(set(data.keys())):
            print "req params error"
            ret_data[0]["status"] = status.REQ_ERR
        else:
            if data["req"] == "reg_user":
                ret_data = reg_user.handler(client,ip_str,data)
            elif data["req"] == "login":
                ret_data = login.handler(client,ip_str,data)
                
    except:
        ret_data[0]["status"] = status.REQ_ERR
    ret_data[0] = json.dumps(ret_data[0])
    ret_data[2] = json.dumps(ret_data[2])
    return ret_data


# 客户端连接超时处理
def timeout(client,ip_str):
    print "timeout fd:{} ip:{}".format(client,ip_str)


# 连接异常
def error(client,ip_str):
    print "error fd:{} ip:{}".format(client,ip_str)